import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

/// 扩展 String
extension ExString on String {

  /// 生成 Color
  Color get toColor {
    return Color(int.parse(this, radix: 16) | 0xFF000000);
  }

  /// 生成 MaterialColor
  Color get toMaterialColor {
    Color color = toColor;

    List<double> strengths = <double>[.05];
    Map<int, Color> swatch = <int, Color>{};
    final int r = color.red, g = color.green, b = color.blue;

    for (int i = 1; i < 10; i++) {
      strengths.add(0.1 * i);
    }
    for (var strength in strengths) {
      final double ds = 0.5 - strength;
      swatch[(strength * 1000).round()] = Color.fromRGBO(
        r + ((ds < 0 ? r : (255 - r)) * ds).round(),
        g + ((ds < 0 ? g : (255 - g)) * ds).round(),
        b + ((ds < 0 ? b : (255 - b)) * ds).round(),
        1,
      );
    }
    return MaterialColor(color.value, swatch);
  }

  /// 清除 html 标签
  String get clearHtml {
    return replaceAll(RegExp(r'<[^>]*>'), '');
  }

  /// 判断文本是不是html格式
  bool get isHtml {
    final RegExp htmlRegExp = RegExp(r'<[^>]*>');
    return htmlRegExp.hasMatch(this);
  }

  /// 判断文本是不是手机号(允许110开头)
  bool get isValidPhoneNumber {
    RegExp exp = RegExp(r'^((110)|(13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    return exp.hasMatch(this);
  }

  // 判断是否为远程格式的图片路径
  bool get isRemoteImage {
    // 正则表达式用于匹配包含常见图片文件后缀的 URL
    RegExp imagePattern = RegExp(r'^https?://.*\.(jpg|jpeg|png|gif|bmp|webp|svg|tiff|ico|jfif)$', caseSensitive: false);
    return imagePattern.hasMatch(this);
  }

  /// 判断图片是不是实时拍照上传
  bool get isRealUrl {
    if (isRemoteImage){
      // 去掉图片格式后缀
      String withoutExtension = replaceAll(RegExp(r'\.(jpg|jpeg|png|gif|bmp|webp|svg|tiff|ico|jfif)$', caseSensitive: false), '');
      // 判断 URL 是否以 "_1" 结尾
      return withoutExtension.endsWith("_1");
    }
    return false;
  }

  /// 格式化日期 - yyyy-MM-dd
  String get dateFormatOfyyyyMMdd {
    var date = DateTime.parse(this);
    return DateFormat('yyyy-MM-dd').format(date);
  }

  ///格式化位置距离
  String formatDistance() {
    double distanceInMeters = double.tryParse(this) ?? 0;
    if (distanceInMeters < 1000) {
      return '${distanceInMeters.toStringAsFixed(0)} 米';
    } else {
      double distanceInKilometers = distanceInMeters / 1000;
      return '${distanceInKilometers.toStringAsFixed(1)} km';
    }
  }



}
